package com.cy.store.controller;

import com.cy.store.service.ICartService;
import com.cy.store.util.JsonResult;
import com.cy.store.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @PROJECT_NAME: store
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/11/8 17:10
 */
@RequestMapping("carts")
@RestController
public class CartController   extends  BaseController{

    @Autowired
    private ICartService cartService;

    /**
     * 添加某个商品到购物车
     * @param session
     * @param pid
     * @param amount
     * @return
     */
    @RequestMapping("add_to_cart")
    public JsonResult<Void> addToCart(Integer pid, Integer amount, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行添加到购物车
        cartService.addToCart(uid, pid, amount, username);
        // 返回成功
        return new JsonResult<Void>(OK);
    }

    /**
     * 刷新购物车列表
     * @param ssession
     * @return
     */
    @RequestMapping({"/",""})
    public JsonResult<List<CartVo>> getVoByUid(HttpSession ssession){
        List<CartVo> result = cartService.getVOByUid(getUidFromSession(ssession));
        return new JsonResult<List<CartVo>>(OK,result);
    }

    /**
     * 增加购物车某个商品的数量
     * @param cid
     * @param session
     * @return
     */
    @RequestMapping("{cid}/num/add")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行增加数量
        Integer data = cartService.updateNumByCid(cid, uid, username);
        // 返回成功
        return new JsonResult<Integer>(OK, data);
    }

    /**
     * 减少某个商品的数量
     * @param cid
     * @param session
     * @return
     */
    @RequestMapping("{cid}/num/reduce")
    public JsonResult<Integer> reduceNum(@PathVariable("cid") Integer cid, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行增加数量
        Integer data = cartService.reduceNum(cid,uid,username);
        // 返回成功
        return new JsonResult<Integer>(OK, data);
    }


    /**
     * 刷新购物车列表
     * @param ssession
     * @return
     */
    @RequestMapping("list")
    public JsonResult<List<CartVo>> getVoByCid(Integer[] cids,HttpSession ssession){
        List<CartVo> voByCid = cartService.getVOByCid(getUidFromSession(ssession), cids);
        return new JsonResult<>(OK,voByCid);
    }

}
